package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"github.com/streadway/amqp"
	//"net/url"
)

//Ret ...
type Ret struct {
	Code int    `json:"code,int"`
	Data string `json:"data"`
}

func printRequest(w http.ResponseWriter, r *http.Request) {
	fmt.Println("r.Form=", r.Form) //这些信息是输出到服务器端的打印信息 , Get参数
	fmt.Println("r.url=",r.RequestURI)
	ret := new(Ret)
	//将用户请求的URL发送给RabbitMQ
	send(r.RequestURI)
	ret.Code = 200
	ret.Data = "提交成功"
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	//只获取函数返回值的第一个结果
	retJSON, _ := json.Marshal(ret)
	io.WriteString(w, string(retJSON))
}

func sayMore(w http.ResponseWriter, r *http.Request) {
	//fmt.Println("test")
	r.ParseForm() //解析参数，默认是不会解析的
	printRequest(w, r)
}


func send(msg string){
	// 连接RabbitMQ服务器
	conn, err := amqp.Dial("amqp://guest:guest@127.0.0.1:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()
	// 创建一个channel
	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()

	// 声明一个队列
	q, err  := ch.QueueDeclare(
		"hello",			// 队列名称
		false,			// 是否持久化
		false,		// 是否自动删除
		false,			// 是否独立
		false,nil,
	)
	failOnError(err, "Failed to declare a queue")
	// 发送消息到队列中
	body := msg
	err = ch.Publish(
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing {
			ContentType: "text/plain",
			Body:        []byte(body),
		})
	failOnError(err, "Failed to publish a message")
	fmt.Println("send message success\n")
}

// 帮助函数检测每一个amqp调用
func failOnError(err error, msg string)  {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}

func main() {
	http.HandleFunc("/room/order", sayMore) //设置访问的路径
	err := http.ListenAndServe(":8080", nil)    //设置监听的端口
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
